//
//  PKHomeViewController.swift
//  Panku
//
//  Created by mac on 2017/2/6.
//  Copyright © 2017年 Monster. All rights reserved.
//

import UIKit
import SnapKit
import SDCycleScrollView //轮播图
import MJRefresh//下拉刷新
import Alamofire
import HTHorizontalSelectionList

import ReactiveSwift
import ReactiveCocoa
import Result

import Reachability

//cell重用ID
private let PKHomeViewControllerLiveCellID = "PKHomeViewControllerLiveCellID"
private let PKHomeViewControllerVideoCellID = "PKHomeViewControllerVideoCellID"
private let PKHomeViewControllerTweetCellID = "PKHomeViewControllerTweetCellID"

class PKHomeViewController: PKBaseViewController{

    //MARK:properties
    //viewModel
    var viewModel:PKHomeViewModel?
    
    //tableView headerView
    var headerView = SDCycleScrollView()
    var searchButton = ATAudioInputButton(type: .custom)
    
    //直播tab 0 or 小视频tab 1 or 发现tab 2
    var currentIndex = 0
    //直播数据
    var lives:[PKLiveModel]?
    //小视频数据
    var videos:[PKPublishShortVideoViewModel]?
    //推文数据
    var tweets:[PKTweetModel]?
    
    //tableView
    var tableView:PKBaseTableView = PKBaseTableView { (make) in
        
    }
    
    //MARK: init
    init(viewModel:PKHomeViewModel) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - life circle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        getLives()
        getVideos()
        getTweets()
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        //展示新特性View
        if PKPreferenceServices.isShowedNewFeatureView() == false{
            PKNewFeatureView.show()
        }

    }

    
    override func setupRootView() {
        view.backgroundColor = UIColor.white
    }
    
    override func setupSubViews() {
        view.addSubview(tableView)
        view.addSubview(searchButton)
        
        searchButton.setImage(R.image.home_float_search(), for: .normal)
        searchButton.frame = CGRect(x: 100, y: 100, width: 44, height: 44)
        
        tableView.dataSource = self
        tableView.delegate = self
        //注册 直播 短视频 and 推文 cell
        tableView.register(PKHomeViewControllerLiveCell.self, forCellReuseIdentifier: PKHomeViewControllerLiveCellID)
        tableView.register(PKHomeViewControllerVideoCell.self, forCellReuseIdentifier: PKHomeViewControllerVideoCellID)
        tableView.register(PKHomeViewControllerTweetCell.self, forCellReuseIdentifier: PKHomeViewControllerTweetCellID)

        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            
            switch self.currentIndex {
                //直播
            case 0:
                self.getLives()
                //小视频
            case 1:
                self.getVideos()
                //推文
            case 2:
                self.getTweets()
            default:
                self.getLives()
            }
            
        })
        
        headerView.frame = CGRect(x: 0, y: 0, width: APP_WIDTH, height: 88)
        headerView.delegate = self
        headerView.placeholderImage = nil
        headerView.currentPageDotImage = R.image.home_choice()
        headerView.pageDotImage = R.image.home_no_choice()
        
        //网络方式获取图片URL
//        headerView.imageURLStringsGroup = viewModel!.cycleImageUrls

        //本地加载图片数组
        headerView.localizationImageNamesGroup = viewModel!.images()

        tableView.tableHeaderView = headerView
        
        //设置placeholderView
        let placeholderView = UILabel()
        placeholderView.isHidden = true 
        placeholderView.text = "我是一个placeholderView"
        placeholderView.font = UIFont.systemFont(ofSize: 30)
        placeholderView.textColor = UIColor.red
        placeholderView.frame = CGRect(x: 0, y: 300, width: APP_WIDTH, height: 300)
        tableView.placeholderView = placeholderView
        
    }
    
    override func setupSubViewsConstraints() {
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
    }
    
    override func setupNavigationBar() {
        
        //title
        self.title = ""
        
        //searchBarButton
        let searchBarButton = PKBaseButton.createButton()
        searchBarButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        searchBarButton.setImage(R.image.home_search(), for: .normal)
        searchBarButton.addBlock(for: .touchUpInside) { (_) in

            let searchViewController = UINavigationController(rootViewController: PKHomeSearchViewController(viewModel: self.viewModel!.viewModelForSearchViewController()))
            self.present(searchViewController, animated: true, completion: { 
                //finish Callback
            })
        }
        
        let searchBarButtonItem = UIBarButtonItem(customView: searchBarButton)
        self.navigationItem.rightBarButtonItem = searchBarButtonItem
        
        //imBarButton
        let imBarButton = PKBaseButton.createButton()
        imBarButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        imBarButton.setImage(R.image.home_message(), for: .normal)
        imBarButton.addBlock(for: .touchUpInside) { (_) in
            
            let IMController = PKIMViewController(viewModel: self.viewModel!.viewModelForIMController())
            self.navigationController?.pushViewController(IMController, animated: true)
        }
        
        let imBarButtonItem = UIBarButtonItem(customView: imBarButton)
        
        //locateButton
        let locateButton = PKBaseButton.createButton()
        locateButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        locateButton.setImage(R.image.home_locate(), for: .normal)
        locateButton.addBlock(for: .touchUpInside) { (_) in
            
            //TODO:定位功能
        }
        
        let locateButtonItem = UIBarButtonItem(customView: locateButton)
        
        self.navigationItem.leftBarButtonItems = [locateButtonItem]
        
        //titleView
        let titleView = HTHorizontalSelectionList()
        titleView.frame = CGRect(x: 0, y: 0, width: 250, height: 44)
        titleView.backgroundColor = UIColor.clear
        titleView.dataSource = self
        titleView.delegate = self
        titleView.centerButtons = true//居中
        titleView.bottomTrimHidden = true//隐藏分割线
        titleView.setTitleFont(UIFont.PKFont(Size: 16), for: .normal)
        
        titleView.setTitleColor(UIColor(hexString: "666666")!, for: .normal)
        titleView.setTitleColor(UIColor(hexString: "333333")!, for: .selected)
        self.navigationItem.titleView = titleView
        
    }
    
    override func bindViewModel() {
        

    }
    
    //MARK: - private
    private func getLives() -> Void{
        //获取直播数据
        PKHomeServices.getLivesList().startWithResult { (result) in
            self.lives = result.value
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
        }
    }
    
    private func getVideos() -> Void{
        self.tableView.mj_header.endRefreshing()
        //获取小视频数据
        //        PKHomeServices.getVideosList(queryTime: "").startWithResult { (result) in
        //            self.videos = result.value
        //self.tableView.reloadData()
        //self.tableView.mj_header.endRefreshing()
        //        }
    }
    
    private func getTweets() -> Void{
        //获取发现数据 推文
        PKHomeServices.getTweetsList().startWithResult { (result) in
            self.tweets = result.value
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
        }
    }

}

//SDCycleScrollView delegate
extension PKHomeViewController:SDCycleScrollViewDelegate{
    
    //图片滚动回调
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didScrollTo index: Int) {

    }

    
    //点击图片回调
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        let url = viewModel!.cycleUrls[index]
        let title = viewModel!.cycleTitles[index]
        let tweetController = PKTweetViewController(viewModel: PKTweetViewModel())
        tweetController.title = title
        tweetController.loadURL(urlString: url)
        self.navigationController?.pushViewController(tweetController, animated: true)
    }
}

//tableView dataSource and delegate
extension PKHomeViewController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        switch currentIndex {
        case 0:
            return lives?.count ?? 0
        case 1:
            return videos?.count ?? 0
        case 2:
            return tweets?.count ?? 0
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        
        switch currentIndex {
            //直播
        case 0:
            let cell  = tableView.dequeueReusableCell(withIdentifier: PKHomeViewControllerLiveCellID, for: indexPath)
            let live = lives![indexPath.row]

            return cell
            //短视频
        case 1:
            let cell  = tableView.dequeueReusableCell(withIdentifier: PKHomeViewControllerVideoCellID, for: indexPath)
            let video = videos![indexPath.row]
            return cell
            //推文
        case 2:
            let cell  = tableView.dequeueReusableCell(withIdentifier: PKHomeViewControllerTweetCellID, for: indexPath)
            let tweet = tweets![indexPath.row]
                      return cell
        default:
            return UITableViewCell()
        }
        

    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let liveViewController = PKLiveViewController()
        self.navigationController?.pushViewController(liveViewController, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return viewModel!.heightForRowAt(index: indexPath.row)
        return 188
    }
}

//HTHorizontalSelectionList dataSource delegate
extension PKHomeViewController:HTHorizontalSelectionListDelegate,HTHorizontalSelectionListDataSource{
    func numberOfItems(in selectionList: HTHorizontalSelectionList) -> Int {
        return viewModel!.tabTitles.count
    }
    
    func selectionList(_ selectionList: HTHorizontalSelectionList, titleForItemWith index: Int) -> String? {
        return viewModel!.tabTitles[index]
    }
    
    func selectionList(_ selectionList: HTHorizontalSelectionList, didSelectButtonWith index: Int) {
        //TODO:点击了titleView 的 tab
        self.currentIndex = index
        self.tableView.mj_header.beginRefreshing()
    }
    
    
}




